<template>
    <div class="QuickEntranceView">
        <div class="QuickEntranceView-head">
            <div style="flex: 1"><span v-if="config.showName">{{ config.name }}</span></div>
            <div class="QuickEntranceView-head-button">
                <a-button size="small" v-if="supportCustom && !showBtn" @click="editEntry(true)">{{$ti18('rxList.editBtn','编辑')}}</a-button>
                <template v-if="showBtn">
                    <a-button size="small" type="primary" @click="addEntry()">
                        <plus-outlined/>
                        {{i18n('list.addQuickEntry','添加快捷入口')}}
                    </a-button>
                    <a-button size="small" :loading="saveLoading" @click="saveEntry()">{{i18n('list.save','保存')}}</a-button>
                    <a-button size="small" @click="listSort()">{{i18n('list.sort','排序')}}</a-button>
                    <a-button size="small" @click="reduction()">{{i18n('list.restoreConfig','还原配置')}}</a-button>
                    <a-button size="small" @click.stop="editEntry(false)">{{$ti18('rxForm.cancelBtn','取消')}}</a-button>
                </template>
            </div>
        </div>
        <div class="QuickEntranceView-center">
            <div class="QuickEntranceView-img">
                <div class="QuickEntranceView-img-name"
                     :style="styleBackgroundImage(config)">
                    <div class="QuickEntranceView-span" :style="getStyle()">{{ config.bannerText.text }}</div>
                </div>
            </div>
            <div class="QuickEntranceView-list">
                <a-carousel class="QuickEntranceView-carousel">
                    <div class="QuickEntranceView-carousel-list" v-for="_item in curList">
                        <div @click="onClick(item)" :style="dropStyle()"
                             class="QuickEntranceView-list-center"
                             data-drop="move"
                             data-effect="copy"
                             draggable="true"
                             :id="item.key"
                             v-for="(item,index) in _item" :key="index">
                            <div :style="{'background':item.background.color}" class="QuickEntranceView-icon">
                                <rx-icon-show :icon="getIcon(item)"></rx-icon-show>
                            </div>
                            <div class="QuickEntranceView-name">{{ item.name }}</div>
                        </div>
                    </div>
                </a-carousel>
            </div>
            <a-tooltip>
                <template #title>
                    <span>{{i18n('list.dragHereDelete','拖拽到此处删除')}}</span>
                </template>
                <div data-drop="copy" v-if="showBtn" class="QuickEntranceView-delete">
                    <div style="display: flex;align-items: center;justify-items: center;">
                        <rx-icon-show icon="icon-lineVue3_delete"></rx-icon-show>
                    </div>
                </div>
            </a-tooltip>
        </div>
    </div>
</template>

<script>
import { mapState } from 'pinia'
import {Util,TokenUtil} from '@lowcode/jpaas-base-lib';
import QuickEntranceDialog from "./QuickEntranceDialog.vue";
import InsPortalDefApi from "@/common/api/portal/insPortalDef.js";
import useMain from "../../../../../../stores/useMain";
import MenuFunc from "@/views/layout/js/MenuFunc.js";
import QuickSortDialog from "./QuickSortDialog.vue";
export default {
    name: "QuickEntranceView",
    mixins:[MenuFunc],
    props: {
        config:{},
        portalId:{}
    },
    data() {
        return {
            entryList: [],//入口列表
            showBtn: false,
            saveLoading: false,
            quickEntrance: "",//个人的配置
        }
    },
    computed:{
        ...mapState(useMain,['menus','curApp']),
        supportCustom() {
            //允许自定义
            return this.config.supportCustom || false;
        },
        curList(){
            let arr = [],{ entryList } = this ;
            for (let i = 0 ;i< entryList.length ;i++){
                let idx = Math.floor(i / 8)
                arr[idx]? arr[idx].push(entryList[i]) : arr[idx] = [entryList[i]]
            }
            return arr ;
        }
    },
    created() {
        this.init();
        this.bindDrag();
    },
    mounted() {

    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "quickEntrance", key);
        },
        listSort(){
            Util.open({
                curVm:this,
                component:QuickSortDialog,
                data:{
                    list:this.entryList
                },
                widthHeight:['400px','500px']
            },(action,data)=>{
                if(action === 'ok'){
                    this.entryList = [...data]
                }
            })
        },
        bindDrag(){
            this.$nextTick(()=>{
                const containerBox = document.querySelector('.QuickEntranceView-center');
                let boxId = null;
                containerBox.ondragstart = (e) => {
                    e.dataTransfer.effectAllowed = e.target.dataset.effect;
                    boxId = e.target.id
                };
                containerBox.ondragover = (e) => {
                    //  阻止默认行为 这里就是开启表格的drop事件
                    e.preventDefault();
                };
                containerBox.ondragenter = (e) => {
                    console.log('111---进入拖拽')
                };

                // 拖拽放手 执行一次
                containerBox.ondrop = (e) => {
                    const dropNode = this.getDropNode(e.target);
                    if (dropNode && dropNode.dataset.drop === e.dataTransfer.effectAllowed) {
                        if (dropNode.dataset.drop === "copy" && boxId) {
                            //拖拽到删除按钮上去松手删除
                            let _idx = this.entryList.findIndex(item=>item.key === boxId);
                            this.entryList.splice(_idx,1)
                            this.$forceUpdate()
                        }
                    }
                };
            })
        },
        // 判断父元素
        getDropNode(node) {
            while (node) {
                if (node.dataset && node.dataset.drop) {
                    return node;
                }
                node = node.parentNode;
            }
        },
        init() {
            InsPortalDefApi.getQuickEntrance(this.config.alias).then(res => {
                let arr = [];
                this.quickEntrance = res;
                if (res && res.id) {
                    arr = res.config ? JSON.parse(res.config) : []
                } else if (this.config.items){
                    arr = this.config.items;
                }
                this.getEntryList(arr);
            }).catch(() => {
                if (this.config.items) {
                    this.getEntryList(this.config.items);
                }
            });
        },
        getEntryList(list) {
            this.entryList = [];
            let entryList_ = Util.deepClone(list);
            //计算菜单 判断菜单是否有权限
            if (this.quickEntrance.menus) {
                for (let i = 0; i < entryList_.length; i++) {
                    if (entryList_[i].type === "menu") {
                        let menu = this.quickEntrance.menus.find(item =>entryList_[i].key === item.id);
                        if (menu) {
                            this.entryList.push(entryList_[i]);
                        }
                    } else {
                        this.entryList.push(entryList_[i]);
                    }
                }
            } else {
                this.entryList = [];
            }
        },
        openMain(menu){
            let {appId} = this.curApp;
            //打开主应用
            let data = {
                appId,
                ...menu,
                title:menu.name,
                name:menu.name,
                menuNavType:2,
                randomKey:Util.randomId()
            }
            //表示从当前子应用的首页触发的事件
            window.microApp && window.microApp.dispatch(data)
        },
        onClick(item) {
            if (!item.key) {
                return;
            }
            let curApp = this.curApp ;
            if (item.type === 'menu') {
                let menu = this.menus.find(obj=>obj.id===item.key);
                if (!menu) { return }
                //弹窗
                if(menu.showType==="POP_WIN"){
                    this.openPopWin(menu);
                }else if(menu.showType==="NEW_WIN"){//新窗口
                    //isMicroApp，表示是否是内嵌微前端进来的微应用，在layoutMethods.js中dataListener方法设置的
                    if(curApp && curApp.isMicroApp){
                        this.openMain(menu)
                    }else {
                        this.openNewWin(menu);
                    }
                }else {
                    //isMicroApp，表示是否是内嵌微前端进来的微应用，在layoutMethods.js中dataListener方法设置的
                    if(curApp && curApp.isMicroApp){
                        this.openMain(menu)
                    }
                    this.handNavigation(menu);
                    //路由跳转
                    this.openUrl({...menu,isPanel:true});
                }
            } else {
                window.open(item.key, '_blank');
            }
        },
        //编辑、取消
        editEntry(val) {
            this.showBtn = val;
        },
        addEntry() {
            let self = this;
            let conf = {
                component: QuickEntranceDialog,
                title: "添加快捷入口",
                widthHeight: ['810px', '600px'],
                curVm: this,
                zIndex: 9,
                data: {menus: this.quickEntrance ? this.quickEntrance.menus : ""}
            };
            Util.open(conf, function (action, data) {
                if (action !== "ok") {
                    return;
                }
                let item = self.entryList.find(obj => obj.key === data.key)
                if (item) {
                    this.$message.warning("当前快捷入口已存在！");
                    return;
                }
                self.entryList.push(data);
            });
        },
        delEntry(index) {
            this.entryList.splice(index, 1);
        },
        //还原管理员配置
        reduction() {
            let self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                content: "你确定要还原成初始配置吗？",
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                keyboard: true,
                zIndex: 99999,
                onOk: function () {
                    InsPortalDefApi.delByAlias(self.config.alias).then(res=>{
                        self.init();
                        self.showBtn=false;
                    });
                },
                onCancel() {
                },
            })
        },
        saveEntry() {
            this.saveLoading = true;
            let appId = this.curApp ? this.curApp.appId : "";
            let obj = "";
            if (this.quickEntrance && this.quickEntrance.id) {
                obj = Util.deepClone(this.quickEntrance);
                obj.config = JSON.stringify(this.entryList);
            } else {
                obj = {
                  config: JSON.stringify(this.entryList),
                  appId: appId,
                  alias: this.config.alias,
                  name: this.config.name,
                  portalId: this.portalId
                }
            }
            InsPortalDefApi.saveQuickEntrance(obj).then(res => {
                if(res.success){
                    this.saveLoading = false;
                    this.init();
                    this.showBtn=false;
                }else {
                    this.saveLoading = false;
                }
            });
        },
        getStyle() {
            let style = {
                fontSize: this.config.bannerText.fontSize + 'px',
                color: this.config.bannerText.fontColor,
                fontWeight: this.config.bannerText.fontWeight
            };
            return style
        },
        styleBackgroundImage(config){
            let style = {};
            if(config.banner.type =='system'){
                style = {backgroundImage: 'url(' + import.meta.env.JPAAS_BASE_URL + "/image/fastImg/"+config.banner.systemImage+".png"+ ')'}
            }else if(config.banner.customImage){
                let token = TokenUtil.getToken();
                style = {backgroundImage:'url(/api/api-system/system/core/sysFile/previewFile?fileId=' +Util.encryptWord(config.banner.customImage)+ '&accessToken='+token+')'}
            }
            return style
        },
        getFilePath(fileId){
            let token = TokenUtil.getToken();
            fileId=Util.encryptWord(fileId);
            return "/api/api-system/system/core/sysFile/previewFile?fileId=" + fileId + "&accessToken=" + token;
        },
        dropStyle(){
            let style = {
                width:'calc('+100/this.config.lineNumber+'% - 10px)'
            };
            return style
        },
        getIcon(item){
            let icon="";
            try {
                icon=JSON.parse(item.background.icon).icon
            }catch (e){
                icon=item.background.icon;
            }
            return icon;
        }
    },
    watch: {
        config: {
            handler: function (o, ol) {
                this.init();
            },
            deep: true
        }
    },
}
</script>

<style scoped>
.QuickEntranceView-delete-hover{
    background: #dc3131!important;
    width: 70px!important;
    margin-left: 0px!important;
}
.QuickEntranceView-delete-name{
    writing-mode: vertical-rl; /* 文字从上到下，从右到左 */
    transform: rotate(180deg);
    text-align: center;
    color: #ffffff;
    font-size: 12px;
}
.QuickEntranceView {
    padding: 10px;
}

.QuickEntranceView-head {
    font-size: 16px;
    color: #282c3c;
    font-weight: bold;
    display: flex;
    align-items: center;
}

.QuickEntranceView-head-button {
    display: flex;
}

.QuickEntranceView-head-button button {
    margin-left: 10px;
}

.QuickEntranceView-center {
    display: flex;
    margin-top: 10px;
}

.QuickEntranceView-img {
    width: 440px;
    height: 162px;
    border-radius: 8px;
    overflow: hidden;
}

.QuickEntranceView-img-name {
    width: 440px;
    height: 162px;
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    overflow: hidden;
}

.QuickEntranceView-span {
    display: block;
    margin-left: 25px;
    width: 224px;
}

.QuickEntranceView-list {
    flex: 1;
    display: flex!important;
    grid-gap: 10px;
    flex-wrap: wrap;
    padding-left: 10px;
    overflow: hidden;
}
.QuickEntranceView-carousel-list{
    flex: 1;
    display: flex!important;
    flex-wrap: wrap;
    grid-gap: 10px;
}
.QuickEntranceView-list-center {
    height: 76px;
    background-color: #eff3fc;
    border-radius: 8px;
    overflow: hidden;
    display: flex;
    align-items: center;
    cursor: pointer;
}

.QuickEntranceView-list-center:hover{
    background: #dae3f8;
}
.QuickEntranceView-icon {
    width: 32px;
    height: 32px;
    background-color: #4285f4;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;
    margin-left: 10px;
}
.QuickEntranceView-icon span{
    display: flex;
    align-items: center;
    justify-content: center;
}
.QuickEntranceView-name {
    flex: 1;
    overflow: hidden;
    font-size: 15px;
    color: #282c3c;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    margin: 0px 10px;
    text-align: left;
}

.QuickEntranceView-delete {
    width: 60px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: white;
    background: #ff5151;
    border-radius: 10px 0px 0px 10px;
    margin-left: 10px;
    font-size: 22px;
}

.QuickEntranceView-center-top {
    margin-bottom: 10px;
}
/*---------*/
.QuickEntranceView-carousel{
    height: 168px;
    width: 100%;
}
.QuickEntranceView-carousel >>> .slick-slide {
    height: 168px;
    width: 100%;
    overflow: hidden;
}
.QuickEntranceView-carousel >>> .slick-dots{
    top:166px!important;
}
.QuickEntranceView-carousel >>> .slick-dots li.slick-active button{
    background: #4285f4!important;
}
.QuickEntranceView-carousel >>> .slick-dots li button{
    background: #8f8d8d!important;
}
</style>
